package com.wangsd.web.shop.service;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.query.Sort;
import com.gitee.fastmybatis.core.util.MyBeanUtil;
import com.wangsd.web.shop.entity.Activity;
import com.wangsd.web.shop.entity.Coupon;
import com.wangsd.web.shop.entity.CouponOrder;
import com.wangsd.web.shop.mapper.CouponOrderMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CouponOrderService {
    @Resource
    CouponOrderMapper mapper;
    @Autowired
    CouponService couponService;

    public int saveOrUpdate(CouponOrder couponOrder) {
        if (couponOrder.getId() == null) {
            mapper.saveIgnoreNull(couponOrder);
        }else {
            mapper.updateIgnoreNull(couponOrder);
        }
        return 1;
    }

    public CouponOrder selectByCouponCode(String coupon_id) {
        return mapper.getByColumn("coupon_code", coupon_id);
    }

    public CouponOrder selectByOutTradeNo(String outTradeNo) {
        return mapper.getByColumn("out_trade_no", outTradeNo);
    }

    public List<CouponOrder> selectByMiniOpenid(String miniOpenid, Integer status) {
        Query query = new Query();
        query.eq("t.mini_openid", miniOpenid);
        if (status != null) {
            query.eq("t.status", status);
        }
        query.orderby("t.created_time", Sort.DESC);
        query.join("join coupon t2 on t.stock_id = t2.stock_id");
        List<String> column = Arrays.asList("t.*, t2.available_begin_Time as startTime, t2.available_end_time as endTime, " +
                "t2.transaction_minimum, t2.coupon_pic_url as fileUrl");
        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        List<CouponOrder> list = MyBeanUtil.mapListToObjList(mapList, CouponOrder.class);
        return list;
    }

    public List<CouponOrder> selectByStockId(String stockId) {
        Query query = new Query();
        query.eq("stock_id", stockId);
        query.eq("status", 2);
        List<CouponOrder> list = mapper.list(query);
        return list;
    }

    public long selectByStockIdAndMiniOpenid(String stockId, String miniOpenid) {
        Query query = new Query();
        query.eq("stock_id", stockId);
        query.eq("mini_openid", miniOpenid);
        return mapper.getCount(query);
    }



    public List<CouponOrder> selectPage(CouponOrder queryObj, String sortField, String sortOrder, String loginCode) {
        Query query = new Query();
        query.notEq("t.status", 0);
        if (StringUtils.isNotBlank(queryObj.getParentCode())) {
            query.eq("t.parent_code", queryObj.getParentCode());
        }
        if (StringUtils.isNotBlank(loginCode)) {
            query.likeRight("t.parent_code", loginCode);
        }
        if (StringUtils.isNotBlank(queryObj.getStockId())) {
            query.eq("t.stock_id", queryObj.getStockId());
        }
        if (StringUtils.isNotBlank(queryObj.getStockType())) {
            query.eq("t.stock_type", queryObj.getStockType());
        }
        if (queryObj.getStatus() != null) {
            query.eq("t.status", queryObj.getStatus());
        }
        if (StringUtils.isNotBlank(queryObj.getMiniOpenid())) {
            query.eq("t.mini_openid", queryObj.getMiniOpenid());
        }
        if (StringUtils.isNotBlank(sortField) && StringUtils.isNotBlank(sortOrder)) {
            String column = sortField;
            if ("createdTime".equals(sortField)){
                column = "t.created_time";
            }
            else if ("consumeTime".equals(sortField)){
                column = "t.consume_time";
            }
            else if ("status".equals(sortField)){
                column = "t.status";
            }
            query.orderby(column, "ascend".equals(sortOrder) ? Sort.ASC : Sort.DESC);
        }
        query.orderby("t.created_time", Sort.DESC);

//        query.join("left join member t2 on t.mini_openid = t2.mini_openid");
//        List<String> column = Arrays.asList("t.*, t2.mobile");
//        List<Map<String, Object>> mapList = mapper.listMap(column, query);
//        List<CouponOrder> list = MyBeanUtil.mapListToObjList(mapList, CouponOrder.class);
        List<CouponOrder> list = mapper.list(query);
        return list;
    }

    /**
     * 定时删除未支付的订单
     */
    @Transactional
    public void deleteByStatus() {
        List<CouponOrder> list = mapper.selectByStatus();
        for (CouponOrder couponOrder : list) {
            Coupon coupon = couponService.selectByStockId(couponOrder.getStockId());
//            coupon.setDistributedCoupons(coupon.getDistributedCoupons() - 1);
//            couponService.update(coupon);
            couponService.updateDistributedCouponsSub(coupon.getId());
            mapper.deleteById(couponOrder.getId());
        }
    }

    /**
     * 发放成功之后保存记录
     * @param coupon
     * @param couponOrderId
     * @param miniOpenid
     * @param nickName
     * @param outTradeNo
     * @param couponCode
     */
    public void saveCouponOrder(Coupon coupon, Long couponOrderId, String miniOpenid, String nickName,
                                String avatarUrl, String outTradeNo, String couponCode, String transactionId) {
        CouponOrder couponOrder = new CouponOrder();
        couponOrder.setId(couponOrderId);
        couponOrder.setParentCode(coupon.getParentCode());
        couponOrder.setStockId(coupon.getStockId());
        couponOrder.setStockName(coupon.getStockName());
        couponOrder.setCouponAmount(coupon.getCouponAmount());
        couponOrder.setMiniOpenid(miniOpenid);
        couponOrder.setNickName(nickName);
        couponOrder.setAvatarUrl(avatarUrl);
        couponOrder.setCouponCode(couponCode);
        couponOrder.setOutTradeNo(outTradeNo);
        couponOrder.setStockType(coupon.getStockType());
        couponOrder.setPrice(coupon.getAmount());
        couponOrder.setStatus(1);
        couponOrder.setTransactionId(transactionId);
        if (couponOrderId == null) {
            mapper.saveIgnoreNull(couponOrder);
        } else {
            mapper.updateIgnoreNull(couponOrder);
        }

    }

    /**
     * 查询过期的券
     */
    public List<CouponOrder> selectByGuoqi() {
        Query query = new Query();
        query.eq("t.status", 1);
        query.join("join coupon t2 on t.stock_id = t2.stock_id");
        query.lt("t2.available_end_time", new Date());
        List<String> column = Arrays.asList("t.*", "t2.is_refund");
        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        List<CouponOrder> list = MyBeanUtil.mapListToObjList(mapList, CouponOrder.class);
        return list;
    }

    /**
     * 更新已过期的券
     * @param ids
     */
    public void updateByGuoqi(List<Long> ids) {
        Query query = new Query();
        query.in("id", ids);
        CouponOrder couponOrder = new CouponOrder();
        couponOrder.setStatus(3);
        mapper.updateByQuery(couponOrder, query);
    }

}
